--[[ Order of things in the table
Object[1] = Xs
Object[2]= Ys
Object[3]= Xv
Object[4]= Yv
Object[5]= Xa
Object[6]= Ya
Object[7]= Speed
Object[8]= vAngle
Object[9]= radius
]]

function love.load()
	AllBalls = {}
	e = 0.5
	BounceAngle = 0
	DT = 1
	g = 0
	NumberBalls = 10
	ballSize = 20
	reset()
end

function love.update(dt)
	NumberBalls = # AllBalls
	for i=1,NumberBalls,1 do
		doPhysics(AllBalls[i], dt)
		for q=i,NumberBalls,1 do
			if i ~= q then
				WillCollide(AllBalls[i], AllBalls[q])
			end
		end
	end
	DT = dt
end

function bounce(theta3, object)
	object[8] = 2*theta3 - object[8]
	object[3] = e*object[7]*math.sin(object[8])
	object[4] = e*object[7]*math.cos(object[8])
end

function bounceoffball(theta, objectA, objectB)
	--assuming Vangle measured clockwise from top
	local Ui = objectA[3] - objectB[3]
	local Vj = objectA[4] - objectB[4]
	local Xmod = ((e + 1) * ((Ui*math.sin(theta)) + (Vj*math.cos(theta)))) / 2
	local Pi = Ui - (Xmod*math.sin(theta))
	local Qj = Vj - (Xmod*math.cos(theta))
	objectA[3] =  objectB[3] + Pi
	objectA[4] =  objectB[4] + Qj
	objectB[3] = objectB[3] + Xmod*math.sin(theta)
	objectB[4] = objectB[4] + Xmod*math.cos(theta)

	-- Do a tick of physics to move the balls away from one another
	objectA[1] = objectA[1] + objectA[3]*DT
	objectA[2] = objectA[2] + objectA[4]*DT
	objectB[1] = objectB[1] + objectB[3]*DT
	objectB[2] = objectB[2] + objectB[4]*DT
end

function doPhysics (object)
	object[1] = object[1] + object[3]*DT
	object[2] = object[2] + object[4]*DT
	object[3] = object[3] + object[5]*DT
	object[4] = object[4] + (g + object[6])*DT
	object[7] = math.sqrt(object[4]*object[4] + object[3]*object[3])
	object[8] = math.atan2(object[3], object[4]) --angle measured clockwise from horizontal
	
	if object[1] > 700 and object[3] > 0 then
		bounce(0, object)
	end
	if object[1] < 100 and object[3] < 0 then
		bounce (math.pi, object)
	end
	if object[2] > 500 and object[4] > 0 then
		bounce(math.pi / 2, object)
	end
	if object[2] < 100 and object[4] < 0 then
		bounce(3 * math.pi / 2, object)
	end
end

function WillCollide (Object1, Object2)
	if  ((Object1[1]-Object2[1])^2 + (Object1[2]-Object2[2])^2) < (Object1[9] + Object2[9])^2 then
		local BounceAngle = math.atan2((Object1[1]-Object2[1]), (Object1[2]-Object2[2]))
		bounceoffball(BounceAngle, Object2, Object1)
		doPhysics(Object1, DT)
		doPhysics(Object2, DT)
	end
end

function addBall (x, y)
	NumberBalls = NumberBalls + 1
	local NewBall = { x,y,math.random(-300, 300),math.random(-300, 300),0,0,0,0,20 }
	AllBalls[NumberBalls] = NewBall
end
	
function reset ()
	for h=1,NumberBalls,1 do
		local Ball = { math.random(100, 700),math.random(100, 500),math.random(-300, 300),math.random(-300, 300),0,0,0,0,ballSize }
		AllBalls[h] = Ball
	end
end
